import Vue from 'vue';
import store from '@/store/index';
import { generateRandomId } from '@/utils/index';
import { getGameInfoByGameCode } from '@/utils/service';
import router from '@/router/index';

// 事件发射器 - 用于处理其他消息
class Emitter {
  constructor() {
    this.listeners = [];
  }

  on(handler) {
    if (typeof handler === 'function' && !this.listeners.includes(handler)) {
      this.listeners.push(handler);
    }
  }

  off(handler) {
    this.listeners = this.listeners.filter((l) => l !== handler);
  }

  emit(data) {
    this.listeners.forEach((handler) => handler(data));
  }
}
export const otherMessageHandler = new Emitter();

// 处理聊天消息
function handleChatMessage(message) {
  if (!message.data.miaoBless) {
    return;
  }
  message.data.id = generateRandomId();
  store.commit('live/addChat', {
    id: message.data.id,
    color: message.data.color,
    headImg: message.data.miaoHeadUrl,
    content: message.data.miaoBless,
    userName: message.data.miaoName.length > 4 ? `${message.data.miaoName.slice(0, 4)}...` : message.data.miaoName,
    giftImg: message.data.miaoTuUrl,
    photoUrl: message.data.pictureUrl,
    miaoVip: store.state.live.liveId === message.data.miaoVipSplid ? message.data.miaoVip : '',
    vipLevel: message.data.miaoVipLevel,
    relativeType: message.data.miaoType,
    currentStatus: message.data.miaoPosition,
    deskNum: message.data.miaoTableNumber,
    sendTime: message.data.sendTime
      || message.data.msgTime
      || message.data.createTime
      || message.data.addTime
      || message.data.miaoTime
      || message.data.time
      || Date.now(),
  });
}
// 处理礼物相关的消息
function handleGiftMessage(message) {
  console.log('礼物消息:', message);

  // 照片礼物
  if (message.data.miaoLwId.indexOf('Miao_Tp') > -1) {
    // 字段处理 照片显示pictureUrl 礼物显示miaoTuUrl
    message.data.pictureUrl = message.data.miaoTuUrl;
    message.data.miaoTuUrl = '';
    handleChatMessage(message);
  } else if (message.data.miaoLwId.indexOf('Miao_Bq') > -1) {
    let tmpRocketType;
    if (message.data.miaoLwId.indexOf('Miao_Bq_2') > -1) {
      tmpRocketType = 1;
    } else if (message.data.miaoLwId.indexOf('Miao_Bq_3') > -1) {
      tmpRocketType = 2;
    } else {
      tmpRocketType = 0;
    }
    Vue.prototype.$createRocketDanmu({
      name: message.data.miaoName,
      headImg: message.data.miaoHeadUrl,
      content: message.data.miaoBless,
      rocketType: tmpRocketType,
    });
    handleChatMessage(message);
  } else if (message.data.miaoLwId.indexOf('Miao_Bp') > -1) {
    let tmpBapinType;
    const bapinTList = store.state.live.bapinTypeList;
    const bapinTListLen = bapinTList.length;
    for (let i = 0; i < bapinTListLen; i += 1) {
      if (bapinTList[i].giftId === message.data.miaoLwId) {
        tmpBapinType = i;
        break;
      }
    }
    const tmpTime = parseInt(bapinTList[tmpBapinType].shijian, 10);
    Vue.prototype.$createLoveBapin({
      name: message.data.miaoName,
      headImg: message.data.miaoHeadUrl,
      content: message.data.miaoBless,
      bapinType: tmpBapinType,
      time: tmpTime,
    });
    handleChatMessage(message);
  } else {
    const tmpAllList = store.state.live.giftList01.concat(store.state.live.giftList02).concat(store.state.live.giftList03);
    const tmpGift = tmpAllList.find((item) => item.giftconst === message.data.miaoLwId);
    if (message.data.miaoBless) {
      handleChatMessage(message);
    }
    message.data.miaoBless = tmpGift.giftname;
    message.data.miaoTuUrl = tmpGift.imglink;
    handleChatMessage(message);

    store.commit('live/addToGiftQueue', {
      userName: message.data.miaoName,
      headImg: message.data.miaoHeadUrl,
      ...tmpGift,
    });
  }
}
// 处理游戏相关的消息
function handleGameMessage(message) {
  const gameBaseInfo = getGameInfoByGameCode(message.data.playInfo);
  store.commit('game/setGameInfo', {
    currentGameCode: message.data.playInfo,
    enterType: gameBaseInfo.enterType,
    gameUrl: gameBaseInfo.gameUrl,
    needShake: gameBaseInfo.needShake,
  });
  if (message.data.miaoState === '1') {
    // 防止页面上本来就有游戏开始按钮
    store.commit('app/setGameBtnVisible', false);
    // 游戏等待中
    if (message.data.playInfo !== 'sign') {
      // 游戏按钮出现(游戏不包括签到)
      store.commit('app/setGameBtnVisible', true);
      store.commit('game/setGameStatus', 1);
    }
    router.replace('/');
  } else if (message.data.miaoState === '2') {
    store.commit('game/setGameStatus', 2);
  } else if (message.data.miaoState === '3') {
    store.commit('game/setGameStatus', 3);
    // 游戏按钮消失
    store.commit('app/setGameBtnVisible', false);
    if (message.data.playInfo === 'hdGame') {
      // 空游戏
      router.replace('/');
    }
    if (store.state.app.rcGiftGameCodes.indexOf(message.data.playInfo) === -1 && store.state.app.giftSendVisible) {
      // 每个游戏结束后弹出一次推荐礼物
      store.commit('app/togglePopup', 6);
      store.commit('app/updateRcGiftGameCodes', message.data.playInfo);
    }
  }
}
// 处理进场消息
function handleEnterMessage(message) {
  console.log(store.state.user.userId, message.data.miaoId);
  if (store.state.user.userId === message.data.miaoId) {
    return;
  }
  if (message.data.miaoVipCar) {
    Vue.prototype.$createEnterEffect({
      name: message.data.miaoName,
      headImg: message.data.miaoHeadUrl,
      enterEffectType: message.data.miaoVipCar,
    });
  } else {
    Vue.prototype.$createEnterEffect({
      name: message.data.miaoName,
      headImg: message.data.miaoHeadUrl,
      enterEffectType: 'common',
    });
  }
}
// 处理其他消息
function handleOtherMessage(message) {
  // 触发事件发射器，让组件可以监听这些消息
  otherMessageHandler.emit(message);
}
// 处理消息(汇总方法)
export default function handleMessage(message) {
  console.log('chatMessage:', message);
  switch (message.type) {
    case 'wsya':
      handleChatMessage(message);
      break;
    case 'liwu':
      handleGiftMessage(message);
      break;
    case 'play':
      handleGameMessage(message);
      break;
    case 'jinchang':
      handleEnterMessage(message);
      break;
    default:
      // 处理其他类型的消息（如许愿树抽奖结果通知）
      handleOtherMessage(message);
      break;
  }
}
